<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片视图   el-ard  -->
    <el-card>
      <el-button type="primary">添加按钮</el-button>
      <!--    tab表格-->
      <el-table :data="shuju" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--            {{scope.row.children}}-->
            <!--            栅格-->
            <el-row class="bom" v-for="(itme1) in scope.row.children" :key="itme1.id">
              <!--  :span="5" 占5列   格栅总共24列            一级权限-->
              <el-col :span="5">
                <el-tag closable @close="romove(scope.row,itme1.id)">{{ itme1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--              二,三级权限-->
              <el-col :span="19">
                <!--                通过for循环  渲染二级权限-->
                <el-row :class="[i2 ===0 ? '' : 'bt','zong']" v-for="(item2,i2) in itme1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="romove(scope.row,item2.id)" type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!--                  scope.row 包含角色id  item3.id 能找到权限id -->
                    <el-tag closable @close="romove(scope.row,item3.id)" v-for="(item3,i3) in item2.children"
                            :key="item3.id">{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--            {{ scope.row }}-->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-share">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-delete" @click="showSetRight(scope.row)">分配权限</el-button>
          </template>

        </el-table-column>

      </el-table>
    </el-card>
    <!--    分配权限对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%" @close="guanbishuzu"
    >
      <!--      树行控件-->
      <el-tree  show-checkbox :data="righrlist"
                ref="treeRef"
                :props="defaultProps" node-key="id" default-expand-all
                :default-checked-keys="defkeys"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary"  @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      //所有角色列表数据
      shuju: [],
      //所有权限的数据
      righrlist: [],
      dialogVisible: false,
      //  树行的绑定对象
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      //  默认选中的节点的id值
      defkeys:[],
      //当前即将分配权限的id
      roleID:''
    }
  },
  created() {
    this.getquanxian()


  },
  methods: {
    async getquanxian() {
      const {data: res} = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('请求数据失败')
      }
      this.shuju = res.data
    },
    //删除权限
    async romove(role, rightsid) {
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)  // catch(err =>err) 把错误信息返回给 confirmResult
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.error('已取消删除')
      }
      //${role.id}  role 是接收方法传来的scope.row 这里面包含角色id   所以role.id能直接找到校色id
      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightsid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      role.children = res.data

    },
    //展示分配权限的对话框的  显示与隐藏
    async showSetRight(role) {
      this.roleID = role.id
      // 首先获取所有权限的数据  在弹出对话框
      const {data: res} = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('请求数据失败')
      }
      this.righrlist = res.data
      //递归获取三级节点id
        this.gitkeys(role, this.defkeys)
      this.dialogVisible = true
    },
  //  通过递归，来获取所有三级权限的id  并保存到defkeys中
    //如果当前node不包含children 说明是三级节点
    // 把node里面的id 给arr
    gitkeys (node,arr) {

      if (!node.children){
        return arr.push(node.id)
      }
    //  如果没有return  说明不是三级节点  进一步调用递归来获取最后的三级节点
    //其次循环node里面所有的数组  每循环一项拿到这个子节点item  在调用当前那个递归函数
    //  把当前的item传进去 数组也传进去
      node.children.forEach(item =>
        this.gitkeys(item,arr)
      )
    },
    //关闭分配权限时   清空数组
    guanbishuzu () {
      //防止npm重复id
      this.defkeys = []
    },
    //点击为角色分配权限
   async  allotRights () {
      const keys = [

          ...this.$refs.treeRef.getCheckedNodes(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)

      const idStr = keys.join(',')//把拿到的id以英文逗号拼接  赋值给idStr
      const {data:res} = await this.$http.post(`roles/${this.roleID}/rights`,{rids:idStr})
     console.log( res)
     console.log("------")
     if (res.meta.status !== 200){
       return this.$message.error('分配权限失败')
     }
     this.$message.success('更新权限成功')
     this.getquanxian()
     this.dialogVisible = false
    }
  },

}
</script>

<style lang="less" scoped>
.bom {
  display: flex;
  align-items: center;
  border-top: 1px solid #eeeeee;
  border-bottom: 1px solid #eeeeee;
}

.bt {
  border-top: 1px solid #eeeeee;
}

.el-tag {
  margin: 7px;
}

.zong {
  display: flex;
  align-items: center;
}
</style>